// import { getList } from '@/api/table'
import {downloadExcel, Get, PostGetData} from '@/api/comm'
import {queryUserInfoApi, queryUserInfoByOrgId} from '@/api/user'
import {mapGetters} from 'vuex'
import moment from 'moment/moment'

export default {
  filters: {
    splitLevelName(levelName) {
      const value = levelName.split('\\')
      return value.slice(-1)[0]
    }
  },
  data() {
    return {
      id: 'id',
      currentPage: 1, // 分页
      isOrg: '',
      openData: '',
      loadingTable: true,
      dialogFormVisible: false, // 弹出框
      // listLoading: true, // 是否loading
      // 搜索条件
      listQuery: {
        page: 1,
        size: 20,
        total: 0
      },
      total: 30,
      list: [], // 表格数据
      multipleSelection: [], // 多选框选中对象数组
      editorOption: { // 富文本 设置
        modules: {}
      },
      currentDep: {
        levelName: '组织用户'
      },
      positionList: [
        '省公司领导（正）',
        '省公司领导（副）',
        '省公司部门领导（正）',
        '省公司部门领导（副）',
        '省公司三级经理',
        '省公司中心领导（正）',
        '省公司中心领导（副）',
        '省公司部门助理',
        '省公司员工',
        '地市领导（正）',
        '地市领导（副）',
        '地市部门领导（正）',
        '地市部门领导（副）',
        '地市中心领导（正）',
        '地市中心领导（副）',
        '地市部门助理',
        '地市员工',
        '区县领导（正）',
        '区县领导（副）',
        '区县员工',
        '公共用户'
      ],
      queryParam: '',
      supervisionTypes: ['立项阶段', '制定档案阶段', '检查阶段', '报告阶段', '持续跟进阶段']
    }
  },
  watch: {},
  created() {
    this.fetchList()
  },
  methods: {
    /**
     * 日期格式化
     */
    formatTime(time) {
      if (!time) {
        return ''
      }
      return moment(new Date(time)).format("YYYY-MM-DD");
    },
    formatTime2(time) {
      if (!time) {
        return ''
      }
      return moment(new Date(time)).format("YYYY/MM/DD");
    },
    initAddForm() {
    },
    editBtn(e) {
      this.searchForm = e
      this.dialogFormVisible = true
      this.openData = '修改'

      // this.$refs.searchForm.resetFields()
    },
    addBtn() {
      this.dialogFormVisible = true
      this.openData = '添加'
      // this.$refs.searchForm.resetFields()
    },
    // 查询
    onSubmit() {
      this.fetchList()
    },
    // 确定提交表单
    async submitForm(e) {
      this.$refs.searchForm.validate(async valid => {
        if (valid) {
          var urlData
          if (this.openData === '添加') {
            urlData = this.url.add
            this.searchForm.username = this.searchForm.phone
            if (this.currentDep.levelName !== '组织用户') {
              this.searchForm.orgId = this.currentDep.id
              this.searchForm.orgLevel = this.currentDep.levelNum
            } else {
              this.currentDep.id = this.searchForm.orgId
            }
          } else if (this.openData === '修改') {
            urlData = this.url.edit
          }
          const lists = await PostGetData(urlData, this.searchForm)
          if (lists.code !== 200) {
            return
          }
          this.$message.success(this.openData + '成功！')
          this.dialogFormVisible = false
          console.log(this.currentDep)
          this.getUserByOrgId(this.currentDep.orgNo)
        } else {
          return false
        }
      })
    },
    // 获取组织用户
    async getUser(name, id) {
      // this.currentDep = '组织用户' // 标题重置
      const list = await queryUserInfoApi(name, '', id, '') // 获取组织用户
      if (list.code === 200 || list.code === '200') {
        this.participants = list.data
        if (this.participants.length > 0) {
          this.currentDep = this.participants[0].org
        }
        this.userLoading = false
      }
    },
    // 根据组织ID查询对应组织人员信息
    async getUserByOrgId(id, name) {
      const list = await queryUserInfoByOrgId(id, name || '') // 获取组织用户
      if (list.code === 200 || list.code === '200') {
        this.participants = list.data
        this.userLoading = false
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      this.tiao = val
    },
    handleCurrentChange(val) {
      this.ye = val
    },
    // excel
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    downloadCompanyExcel() {
      this.searchForm.ids = []
      if (this.multipleSelection.length == 0) {
        this.$message.error('请选择您要导出的信息')
        return
      }
      var arr = this.multipleSelection
      for (var i = 0; i < arr.length; i++) {
        /* this.ids.push(arr[i].schoolId); */
        this.searchForm.ids.push(arr[i].schoolId)
      }
      const params = {
        // 请求参数 要下载Excel的id
        searchForm: this.searchForm
      }
      var urls = 'question/export'
      downloadExcel(urls, params).then(res => {
        // 调用接口
        // res = res.data
        var blob = new Blob([res], {
          type:
            'application/vnd.openxmlformats-  officedocument.spreadsheetml.sheet;charset=utf-8'
        }) // type这里表示xlsx类型

        var downloadElement = document.createElement('a')
        var href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.href = href
        downloadElement.download = new Date().valueOf() + '.xls' // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href) // 释放掉blob对象
      })
    },
    /* 导入excel*/
    fileSuccess(response, file, fileList) {
      if (response.code !== '200') {
        this.$message({
          message: response.msg,
          type: 'warning'
        })
      } else {
        this.$message({
          message: '导入成功',
          type: 'success'
        })
        this.excelDialog = false
        this.fileList = []
      }
    },
    beforeUpload(file) {
      const suffixs = ['xls', 'xlsx']
      var suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (suffixs.indexOf(suffix) === -1) {
        this.$message({
          message: '上传文件只能是 xls、xlsx格式!',
          type: 'warning'
        })
      }
      return suffixs.indexOf(suffix) !== -1
    },
    submitUpload() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.$refs.upload.submit()
      setTimeout(() => {
        loading.close()
        this.uploadExcel = false
        this.fetchList()
      }, 1000)
      // 发送ajax
    },
    async fetchList(param) {
      const params = {
        ...this.listQuery,
        // param: this.form
        param: param || this.queryParam
      }
      this.loadingTable = true
      const lists = await Get(this.url.list, params)
      console.log(lists)
      this.list = lists.data.records
      this.loadingTable = false
      this.listQuery.total = lists.data.total
    },

    async del(mes) {
      if (this.multipleSelection.length <= 0) {
        this.$message.warning('请选择您要删除的信息')
      } else {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const orgId = []
          let level = ''
          for (let i = 0; i < this.multipleSelection.length; i++) {
            const a = this.multipleSelection[i]
            orgId.push(a.id)
            level = a.level
          }
          const ids = {
            ids: orgId,
            ID: orgId,
            level: level
          }
          const res = await PostGetData(this.url.del, ids)
          this.fetchList(this.form)
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
      }
    }
  }
}
